﻿using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace PlatformNetCore.Entity.Configuration
{
    public static class ConfigurationSetting
    {
        private static IConfiguration configuration;
        public static string GetConnectionString()
        {
            try
            {
                if (configuration == null)
                {
                    var fileName = "appsettings.json";
                    var directory = AppContext.BaseDirectory;
                    directory = directory.Replace("\\", "/");
                    var filePath = $"{directory}/{fileName}";
                    if (!File.Exists(filePath))
                    {
                        var length = directory.IndexOf("/bin");
                        filePath = $"{directory.Substring(0, length)}/{fileName}";
                    }
                    configuration = new ConfigurationBuilder().AddJsonFile(filePath, optional: true, reloadOnChange: true).Build();

                    if(configuration == null)
                    {
                        var builder = new ConfigurationBuilder()
                                       .SetBasePath(AppContext.BaseDirectory)
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                       .AddEnvironmentVariables();
                        configuration = builder.Build();
                    }
                    //configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                    //    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    //    .Build();
                }
                return configuration.GetConnectionString("DefaultConnection");
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }
}
